package jtacck.labmedicine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import jvm.jtacck.db.records.ClientSite;
import jvm.jtacck.db.records.Hospital;
import jvm.jtacck.db.records.ShippingInformation;
import jvm.jtacck.serials.Route;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.Toast;
import android.util.Log;

public class RouteListActivity extends Activity {
    private static String[] routeText = null;
    public static Intent i = null;
    private ExpandableListAdapter mAdapter;
    private ExpandableListView list;

    public static boolean modified = true;

    public static List<String> beginning = new ArrayList<String>();
    public static List<String> current = new ArrayList<String>();
    public static List<String> end = new ArrayList<String>();

    public static String currentHospital = "";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.route_screen);

        list = (ExpandableListView) findViewById(R.id.route_screen_list);

        // list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        OnClickListener listener = new OnClickListener() {
            public void onClick(View view) {
                Bundle extras = new Bundle();
                extras.putString("state", "END");
                Intent intent = new Intent(RouteListActivity.this,
                        ChecklistActivity.class);
                intent.putExtra("jtacck", extras);
                RouteListActivity.this.startActivity(intent);
            }
        };

        ((Button) findViewById(R.id.checkoutbutton))
                .setOnClickListener(listener);

        try {
            Thread.sleep(200);
        } catch (Exception e) {
            Log.i("DEBUG", "THREAD SLEEP ERROR");
        }
        if (MainActivity.route != null && routeText == null) {
            Route r = MainActivity.route;
            List<String> temp = new LinkedList<String>();
            for (Hospital h : r.route.keySet()) {
                List<ClientSite> sites = r.route.get(h);
                LinkedHashMap<ClientSite, List<ShippingInformation>> siteMap = new LinkedHashMap<ClientSite, List<ShippingInformation>>();
                for (ClientSite s : sites) {
                    siteMap.put(s,
                            MainActivity.linker.getShippingList(s).shippingList);
                    temp.add(h.name + " - " + s.name);
                }
                MainActivity.cache.getRouteData().addHospital(h, siteMap);
            }
            routeText = temp.toArray(new String[0]);
            if (routeText.length > 0) {
                current.add(routeText[0]);
                for (String s : routeText) {
                    end.add(s);
                }
                end.remove(0);
            }
        }

        createExpandable();

        list.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {

                if (groupPosition == 1) {
                    int i = childPosition;
                    ExpandableListAdapter temp = parent
                            .getExpandableListAdapter();
                    for (int j = 0; j < groupPosition; j++) {
                        i += temp.getChildrenCount(j);
                    }
                    Route r = MainActivity.route;
                    Bundle extras = new Bundle();
                    if (r != null) {
                        int j = 0;
                        for (Hospital h : r.route.keySet()) {
                            List<ClientSite> sites = r.route.get(h);
                            for (ClientSite s : sites) {
                                RouteData data = MainActivity.cache
                                        .getRouteData();
                                data.addHospital(
                                        h,
                                        new LinkedHashMap<ClientSite, List<ShippingInformation>>());
                                if (i == j) {
                                    MainActivity.currentSite = s;
                                    MainActivity.sList = null;
                                }
                                j++;
                            }
                        }
                    }
                    extras.putSerializable("nextActivity",
                            ChecklistActivity.class);
                    extras.putSerializable("serverRequest",
                            MainActivity.currentSite);
                    extras.putString("state", "SITE");
                    Intent intent = new Intent(RouteListActivity.this,
                            ChecklistActivity.class);
                    intent.putExtra("jtacck", extras);
                    RouteListActivity.this.startActivity(intent);
                }
                return true;
            }

        });

        /*
         * list.setAdapter(new ArrayAdapter(this, R.layout.listview_text_format,
         * routeText)); list.setOnItemClickListener(new RouteListener(this));
         */
    }

    @Override
    protected void onResume() {
        super.onResume();

        /*
         * ((ListView) findViewById(R.id.route_screen_list)) .setAdapter(new
         * MenuAdapter<String>(this, R.layout.listview_text_format, routeText));
         */

        if (MainActivity.linker.hasNextRoute()) {
            MainActivity.route = MainActivity.linker.getNextRoute();
            if (MainActivity.route != null) {
                Route r = MainActivity.route;
                List<String> temp = new LinkedList<String>();
                for (Hospital h : r.route.keySet()) {
                    List<ClientSite> sites = r.route.get(h);
                    LinkedHashMap<ClientSite, List<ShippingInformation>> siteMap = new LinkedHashMap<ClientSite, List<ShippingInformation>>();
                    for (ClientSite s : sites) {
                        siteMap.put(
                                s,
                                MainActivity.linker.getShippingList(s).shippingList);
                        temp.add(h.name + " - " + s.name);
                    }
                    MainActivity.cache.getRouteData().addHospital(h, siteMap);
                }
                routeText = temp.toArray(new String[0]);
                Log.e("CRASHING", temp.size() + " " + routeText.length);
                if (!temp.contains(current.get(0))) {
                    current.clear();
                    end.clear();
                    current.add(temp.get(0));
                    for (String s : temp) {
                        end.add(s);
                    }
                    end.remove(0);
                } else {
                    end.clear();
                    for (int i = temp.indexOf(current.get(0)) + 1; i < temp
                            .size(); i++) {
                        end.add(temp.get(i));
                    }
                }

                createExpandable();
                Toast.makeText(this, "Route has been updated",
                        Toast.LENGTH_SHORT).show();
            }

        }

        list.expandGroup(1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 1:
            return SharedMethods.logoutAlert(this);
        }
        return null;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.text:
            showDialog(1);
            break;
        case R.id.icontext:
            break;
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showDialog(1);
            return true;
        }
        return false;
    }

    private void createExpandable() {

        List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
        List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();

        Map<String, String> curGroupMap = new HashMap<String, String>();
        groupData.add(curGroupMap);
        curGroupMap.put("NAME", "Previous Client Sites");
        List<Map<String, String>> children = new ArrayList<Map<String, String>>();
        Map<String, String> curChildMap = new HashMap<String, String>();
        for (String s : beginning) {
            curChildMap = new HashMap<String, String>();
            children.add(curChildMap);
            curChildMap.put("CS", s);
        }
        childData.add(children);

        curGroupMap = new HashMap<String, String>();
        groupData.add(curGroupMap);
        curGroupMap.put("NAME", "Current Client Sites");
        children = new ArrayList<Map<String, String>>();
        for (String s : current) {
            curChildMap = new HashMap<String, String>();
            children.add(curChildMap);
            curChildMap.put("CS", s);
        }
        childData.add(children);

        curGroupMap = new HashMap<String, String>();
        groupData.add(curGroupMap);
        curGroupMap.put("NAME", "End Client Sites");
        children = new ArrayList<Map<String, String>>();
        for (String s : end) {
            curChildMap = new HashMap<String, String>();
            children.add(curChildMap);
            curChildMap.put("CS", s);
        }
        childData.add(children);

        // Set up our adapter
        mAdapter = new SimpleExpandableListAdapter(this, groupData,
                R.layout.listview_text_format, new String[] { "NAME" },
                new int[] { R.id.listview_text_format }, childData,
                R.layout.listview_text_format, new String[] { "CS" },
                new int[] { R.id.listview_text_format });
        list.setAdapter(mAdapter);

        if (MainActivity.route != null && !current.isEmpty()) {
            Route r = MainActivity.route;
            for (Hospital h : r.route.keySet()) {
                for (ClientSite c : r.route.get(h)) {
                    if ((h.name + " - " + c.name).equals(current.get(0))) {
                        currentHospital = h.address;
                    }
                }
            }
        }

    }
}
